import type { BasicUserInfo } from '@vben-core/typings';

import { useAccessStore } from '@vben/stores';

import { requestClient } from '#/api/request';

export namespace AuthApi {
  /** 公共登录参数 */
  export interface OAuth2Params {
    grant_type?: string;
    client_id?: string;
    client_secret?: string;
  }

  /** 登录接口参数 */
  export interface PasswordLoginParams extends OAuth2Params {
    password?: string;
    username?: string;
    captchaId?: string;
  }

  /** 登录接口返回值 */
  export interface LoginResult {
    access_token: string;
    expires_in: number;
    refresh_token: string;
    refresh_expires_in: number;
  }
}

/**
 * 刷新accessToken
 */
export async function refreshTokenApi() {
  return tokenApi('refresh_token', {
    refresh_token: useAccessStore().refreshToken,
  });
}

/**
 * 登录TOKEN API
 */
export async function tokenApi(grantType: string, data: any) {
  requestClient.isWhiteUrl = true;
  return requestClient.post<AuthApi.LoginResult>(
    '/auth/oauth2/token',
    {
      ...data,
      grant_type: grantType,
      client_id: 'server',
      client_secret: 'secret',
    },
    {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    },
  );
}

/**
 * 退出登录
 */
export async function logoutApi() {
  return requestClient.post('/auth/oauth/logout');
}

/**
 * 获取用户信息
 */
export async function getUserInfoApi() {
  return requestClient.get<BasicUserInfo>('/auth/sysuserinfo');
}

/**
 * 获取用户权限码
 */
export async function getAccessCodesApi() {
  return requestClient.get<string[]>('/auth/codes');
}
